*=============================================================
       ***DID Model***
*=============================================================
use diddata.dta,clear
gen upgrade = 0 // generate 0-1 variable: partnership upgrade
replace upgrade = 1 if year >= policy & !missing(year, policy) 
reg y upgrade if fiter_partner==1, r
est store didbase1
reg y upgrade lnusgdp lnuspopu lnchngdp relation democracy if fiter_partner==1, r
est store didbase2
reghdfe y upgrade lnusgdp lnuspopu lnchngdp relation democracy if fiter_partner==1, absorb(ccode2) cluster(ccode2)
est store didbase3
esttab didbase1 didbase2 didbase3 using DIDbaseline.rtf,b(3) t(3) star(* 0.1 ** 0.05 *** 0.01) stats(N r2 F)  varwidth(35) mtitle(Sentiment Sentiment Sentiment) compress nogap replace

/* Parallel Trend Test */
gen m = year - policy  // Generate time variable
forvalues l = -5(1)10 {
    * Handling negative numbers: Convert '-5' to 'n5', otherwise it cannot be recognized
    local l_clean = abs(`l')
    if `l' < 0 {
        gen event_mn`l_clean' = (m == `l') if !missing(m)
    }
    else {
        gen event_m`l' = (m == `l') if !missing(m)
    }
}
* Using one year before partnership upgrade as the Base
drop event_mn1
gen event_mn1 = 0
reghdfe y event_m* lnuspopu lnusgdp lnchngdp relation democracy if fiter_partner==1, absorb(ccode2) cluster(ccode2 year)

* Test pre- and post- trend
test event_mn5 event_mn4 event_mn3 event_mn2 event_mn1
test event_m0 event_m1 event_m2 event_m3 event_m4 event_m5 event_m6 event_m7 event_m8 event_m9 event_m10
* Draw Parallel Trend figure
coefplot, baselevels omitted ///
    keep(event_m*) ///
    vertical ///
	order(event_mn5 event_mn4 event_mn3 event_mn2 event_mn1 event_m0 ///
	event_m1 event_m2 event_m3 event_m4 event_m5 event_m6) ///
    coeflabels(event_mn5=-5 event_mn4=-4 event_mn3=-3 event_mn2=-2 event_mn1=-1 ///
               event_m0=0 event_m1=1 event_m2=2 event_m3=3 event_m4=4 ///
			   event_m5=5 event_m6=6 event_m7=7 event_m8=8 event_m9=9 event_m10=10) ///
    yline(0, lwidth(vthin) lpattern(solid) lcolor(black)) ///
    xline(5, lwidth(vthin) lpattern(dash) lcolor(black)) ///
    ylabel(, labsize(*0.85) angle(0)) xlabel(, labsize(*0.75)) ///
    ytitle("Dynamic Effects") ///
    xtitle("Partnership Upgrade") ///
    msymbol(O) msize(small) mcolor(gs1) ///
    addplot(line @b @at,lcolor(gs1) lwidth(medthick)) ///
    ciopts(recast(rcap) lwidth(thin) lpattern(dash) lcolor(gs2)) /// 
    graphregion(color(white))

	
*=============================================================
       ***Placebo test: Lag1 and Lag6***
*=============================================================
/// Placebo test: robustness of results tested by randomly allocating policy time
/// Placebo Lag(1)
preserve
tempfile original
save `original'
// Set simulation parameters
local reps 500    // Repeat 500times
set seed 1234
tempname simresults
postfile `simresults' pvalue coef se using "placebo.dta", replace
// Actual time range of partnership upgrade
sum policy if fiter_partner==1
local min_year = r(min)
local max_year = r(max)
// cycle simulation 500times
forvalues i = 1/`reps' {
    use `original', clear
    
    // Randomly generate false policy time just for treatment
    bys ccode2: gen policy_fake = cond(fiter_partner==1, ///
        floor(runiform()*(`max_year'-`min_year'+1))+`min_year', /// 
        .)  //
    
    gen m_fake = year - policy_fake
    forvalues l = -5(1)10 {
        local l_clean = abs(`l')
        if `l' < 0 {
            capture drop event_fn`l_clean'
            gen event_fn`l_clean' = (m_fake == `l') if !missing(m_fake)
        }
        else {
            capture drop event_f`l'
            gen event_f`l' = (m_fake == `l') if !missing(m_fake)
        }
    }
    drop event_fn1      // Maintain a Base setting consistent with the original
    gen event_fn1 = 0 
    
    // regress Placebo
    capture noisily reghdfe y event_f* event_fn1 lnuspopu lnusgdp lnchngdp /// 
        relation democracy if fiter_partner==1, absorb(ccode2) cluster(ccode2 year)
        
    // Store simulation results
    if _rc == 0 {
        matrix b = e(b)
        matrix V = e(V)
        local coef = b[1, colnumb(b, "event_f1")]
        local se = sqrt(V[colnumb(b, "event_f1"), colnumb(b, "event_f1")])
        local pvalue = 2 * (1 - normal(abs(`coef') / `se'))
        
        post `simresults' (`pvalue') (`coef') (`se')
    }
    else {
        post `simresults' (. . .)
    }
}
postclose `simresults'
* Draw Placebo test figure
use placebo.dta,clear
twoway (scatter pvalue coef, msymbol(smcircle_hollow) mcolor(black))       (kdensity coef,yaxis(2) lp(solid)) , ///
       title("") ///
       xlabel(-0.1(0.05)0.1 -0.1 "-0.1" -0.05 "-0.05" 0 "0" 0.05 "0.05" 0.1 "0.1",format(%7.1f) angle(0)) ///
       ylabel(0(0.2)1, format(%7.1f) angle(0) nogrid axis(1)) ///
       ylabel(0(10)50, format(%7.1f) angle(0)  nogrid axis(2)) ///
       xtitle("Coefficient") ///
       ytitle("p" ,orientation(vertical) axis(1)) ///
       ytitle("Kernel Beta" ,orientation(vertical)  axis(2)) ///
       xline(0, lwidth(0.2) lp(dash))  ///
       xline(0.0264995, lwidth(0.3) lp(solid)) ///
       yline(0.1,lwidth(0.2) lp(dash)) ///
       legend(label(1 "p") label( 2 "Kernel Beta")) ///
       plotregion(style(none)) /// 
       graphregion(color(white))
*-------------------------------------------------------------------
/// Placebo Lag(6)
preserve
tempfile original
save `original'
// Set simulation parameters
local reps 500    // Repeat 500times
set seed 1234
tempname simresults
postfile `simresults' pvalue coef se using "placebo.dta", replace
// Actual time range of partnership upgrade
sum policy if fiter_partner==1
local min_year = r(min)
local max_year = r(max)
// cycle simulation 500times
forvalues i = 1/`reps' {
    use `original', clear
    
    // Randomly generate false policy time just for treatment
    bys ccode2: gen policy_fake = cond(fiter_partner==1, ///
        floor(runiform()*(`max_year'-`min_year'+1))+`min_year', /// 
        .)  //
    
    gen m_fake = year - policy_fake
    forvalues l = -5(1)10 {
        local l_clean = abs(`l')
        if `l' < 0 {
            capture drop event_fn`l_clean'
            gen event_fn`l_clean' = (m_fake == `l') if !missing(m_fake)
        }
        else {
            capture drop event_f`l'
            gen event_f`l' = (m_fake == `l') if !missing(m_fake)
        }
    }
    drop event_fn1      // Maintain a Base setting consistent with the original
    gen event_fn1 = 0 
    
    // regress Placebo
    capture noisily reghdfe y event_f* event_fn1 lnuspopu lnusgdp lnchngdp /// 
        relation democracy if fiter_partner==1, absorb(ccode2) cluster(ccode2 year)
        
    // Store simulation results
    if _rc == 0 {
        matrix b = e(b)
        matrix V = e(V)
        local coef = b[1, colnumb(b, "event_f6")]
        local se = sqrt(V[colnumb(b, "event_f6"), colnumb(b, "event_f6")])
        local pvalue = 2 * (1 - normal(abs(`coef') / `se'))
        
        post `simresults' (`pvalue') (`coef') (`se')
    }
    else {
        post `simresults' (. . .)
    }
}
postclose `simresults'
* Draw Placebo test figure
use placebo.dta,clear
twoway (scatter pvalue coef, msymbol(smcircle_hollow) mcolor(black))       (kdensity coef,yaxis(2) lp(solid)) , ///
       title("") ///
       xlabel(-0.1(0.05)0.1 -0.1 "-0.1" -0.05 "-0.05" 0 "0" 0.05 "0.05" 0.1 "0.1",format(%7.1f) angle(0)) ///
       ylabel(0(0.2)1, format(%7.1f) angle(0) nogrid axis(1)) ///
       ylabel(0(10)50, format(%7.1f) angle(0)  nogrid axis(2)) ///
       xtitle("Coefficient") ///
       ytitle("p" ,orientation(vertical) axis(1)) ///
       ytitle("Kernel Beta" ,orientation(vertical)  axis(2)) ///
       xline(0, lwidth(0.2) lp(dash))  ///
       xline(-0.0329315, lwidth(0.3) lp(solid)) ///
       yline(0.1,lwidth(0.2) lp(dash)) ///
       legend(label(1 "p") label( 2 "Kernel Beta")) ///
       plotregion(style(none)) /// 
       graphregion(color(white))
	   
	   
*=============================================================
       ***Regress Replacing Independent Variable***
*=============================================================
use continuous.dta, clear
forvalues lag = 0/10 {
    capture noisily {
        reghdfe y L`lag'.partner lnuspopu lnusgdp lnchngdp relation democracy ///
            if fiter_partner==1, absorb(ccode2) cluster(ccode2)
    }
}
///Full sample regression
tempfile results
tempname memhold
postfile `memhold' lag coef lb ub using `results', replace

forvalues lag = 0/10 {
    capture noisily {
        reghdfe y L`lag'.partner lnuspopu lnusgdp lnchngdp relation democracy ///
            if fiter_partner==1, absorb(ccode2) cluster(ccode2)
        
        // coefficient & CI
        local coef = _b[L`lag'.partner]
        local se = _se[L`lag'.partner]
        local lb = `coef' - 1.96 * `se'
        local ub = `coef' + 1.96 * `se'
        
        post `memhold' (`lag') (`coef') (`lb') (`ub')
    }
    if _rc != 0 {
        post `memhold' (`lag') (.) (.) (.)
    }
}
postclose `memhold'
///Draw figure of reg coefficient & CI
use `results', clear
twoway (connected coef lag, lcolor(black) mcolor(black)) ///
       (rarea ub lb lag, color(gs12%30)), ///
       legend(off) ///
       xlabel(0(1)10, nogrid) xtitle("") ///
       yline(0, lwidth(0.2) lp(solid)) ///
       title("Full Sample", pos(11) size(medsmall)) ///
       graphregion(color(white)) name(g1, replace)
graph save graph1.gph, replace

///U.S.'s allies sample regression
use continuous.dta, clear
tempfile results
tempname memhold
postfile `memhold' lag coef lb ub using `results', replace

forvalues lag = 0/10 {
    capture noisily {
        reghdfe y L`lag'.partner lnuspopu lnusgdp lnchngdp relation democracy ///
            if fiter_partner==1 & US_ally==1, absorb(ccode2) cluster(ccode2)
        
        // coefficient & CI
        local coef = _b[L`lag'.partner]
        local se = _se[L`lag'.partner]
        local lb = `coef' - 1.96 * `se'
        local ub = `coef' + 1.96 * `se'
        
        post `memhold' (`lag') (`coef') (`lb') (`ub')
    }
    if _rc != 0 {
        post `memhold' (`lag') (.) (.) (.)
    }
}
postclose `memhold'
use `results', clear
twoway (connected coef lag, lcolor(black) mcolor(black)) ///
       (rarea ub lb lag, color(gs12%30)), ///
       legend(off) ///
       xlabel(0(1)10, nogrid) xtitle("") ytitle("") ///
	   yline(0, lwidth(0.2) lp(solid)) ///
       title("U.S. Allies", pos(11) size(medsmall)) ///
       graphregion(color(white)) name(g2, replace)
graph save graph2.gph, replace

///U.S.'s non-ally sample regression
use continuous.dta, clear
tempfile results
tempname memhold
postfile `memhold' lag coef lb ub using `results', replace

forvalues lag = 0/10 {
    capture noisily {
        reghdfe y L`lag'.partner lnuspopu lnusgdp lnchngdp relation democracy ///
            if fiter_partner==1 & US_ally~=1, absorb(ccode2) cluster(ccode2)
        
        // coefficient & CI
        local coef = _b[L`lag'.partner]
        local se = _se[L`lag'.partner]
        local lb = `coef' - 1.96 * `se'
        local ub = `coef' + 1.96 * `se'
        
        post `memhold' (`lag') (`coef') (`lb') (`ub')
    }
    if _rc != 0 {
        post `memhold' (`lag') (.) (.) (.)
    }
}
postclose `memhold'
use `results', clear
twoway (connected coef lag, lcolor(black) mcolor(black)) ///
       (rarea ub lb lag, color(gs12%30)), ///
       legend(off) ///
       xlabel(0(1)10, nogrid) xtitle("") ytitle("") ///
	   yline(0, lwidth(0.2) lp(solid)) ///
       title("Non-U.S. Allies", pos(11) size(medsmall)) ///
       graphregion(color(white)) name(g3, replace)
graph save graph3.gph, replace

graph combine graph1.gph graph2.gph graph3.gph, ///
    rows(3) /// 竖向排列
    ysize(12) xsize(9) /// 调整图形尺寸
    ycommon xcommon /// 统一坐标轴范围
    l1title("Coefficients", placement(left)) /// 左侧主标题
    b1title("Lag Periods", margin(top)) /// 底部主标题
    graphregion(color(white)) ///
    plotregion(margin(zero)) ///
	imargin(tiny) ///
    iscale(0.9)

	
*=============================================================
       ***Mechanism Test***
*=============================================================
///Bootstrap Test
use continuous.dta, clear
keep if fiter_partner==1 & US_ally==1
gen l2par = L2.partner
***in short term; U.S. ALLY
global ControlVariables lnuspopu lnusgdp lnchngdp relation democracy i.ccode2
capture program drop mediation
program mediation, rclass
    syntax [if]
    marksample touse
    
    gsem (lngpr <- l2par $ControlVariables) ///
         (y <- lngpr l2par $ControlVariables) ///
         if `touse', nocaps latent(_none) iter(100)
    
    if e(converged) {
        return scalar indirect = _b[lngpr:l2par]*_b[y:lngpr]
        return scalar direct = _b[y:l2par]
        return scalar total_effect = return(indirect) + return(direct)
    }
    else {
        return scalar indirect = .
        return scalar direct = .
        return scalar total_effect = .
    }
end
set seed 12345
bootstrap indirect=r(indirect) direct=r(direct) total_effect=r(total_effect), ///
    reps(500): mediation
estat boot, bc percentile

***in short term; NON-U.S. ALLY
use continuous.dta, clear
keep if fiter_partner==1 & US_ally~=1
gen l2par = L2.partner
global ControlVariables lnuspopu lnusgdp lnchngdp relation democracy i.ccode2
capture program drop mediation
program mediation, rclass
    syntax [if]
    marksample touse
    
    gsem (lngpr <- l2par $ControlVariables) ///
         (y <- lngpr l2par $ControlVariables) ///
         if `touse', nocaps latent(_none) iter(100)
    
    if e(converged) {
        return scalar indirect = _b[lngpr:l2par]*_b[y:lngpr]
        return scalar direct = _b[y:l2par]
        return scalar total_effect = return(indirect) + return(direct)
    }
    else {
        return scalar indirect = .
        return scalar direct = .
        return scalar total_effect = .
    }
end
set seed 12345
bootstrap indirect=r(indirect) direct=r(direct) total_effect=r(total_effect), ///
    reps(500): mediation
estat boot, bc percentile

***in long term; U.S. ALLY
use continuous.dta, clear
keep if fiter_partner==1 & US_ally==1
gen l6par = L6.partner
global ControlVariables lnuspopu lnusgdp lnchngdp relation democracy i.ccode2
capture program drop mediation
program mediation, rclass
    syntax [if]
    marksample touse
    
    gsem (lngpr <- l6par $ControlVariables) ///
         (y <- lngpr l6par $ControlVariables) ///
         if `touse', nocaps latent(_none) iter(100)
    
    if e(converged) {
        return scalar indirect = _b[lngpr:l6par]*_b[y:lngpr]
        return scalar direct = _b[y:l6par]
        return scalar total_effect = return(indirect) + return(direct)
    }
    else {
        return scalar indirect = .
        return scalar direct = .
        return scalar total_effect = .
    }
end
set seed 12345
bootstrap indirect=r(indirect) direct=r(direct) total_effect=r(total_effect), ///
    reps(500): mediation
estat boot, bc percentile

***in long term; NON-U.S. ALLY
use continuous.dta, clear
keep if fiter_partner==1 & US_ally~=1
reghdfe lngpr L6.partner lnuspopu lnusgdp lnchngdp relation democracy, absorb(ccode2)
reghdfe y lngpr L6.partner lnuspopu lnusgdp lnchngdp relation democracy, absorb(ccode2)